import {
    observable,
    action,
    computed,
    runInAction,
    toJS
} from 'mobx';

import BaseStore from '../BaseStore';
import validationUtil from '@/utils/validation';
import {
    noticeMessage
} from '@utils/common-message';

class Store extends BaseStore {

    @observable username = '';
    @observable realname = '';
    @observable hasRules = 0;
    @observable countData = {};
    @observable currentList;
    @observable isEmptyCondition = true;

    @observable editUserId = '';
    @observable editUsername = '';
    @observable oldUsername = '';
    @observable editRealname = '';
    @observable editPassword = '';
    @observable editCardNo = '';
    @observable editFaceImgData = null;
    @observable editCertImgsData = null;
    // 打开弹框的类型
    //     1 -- 新增用户
    //     2 -- 编辑用户
    //     3 -- 指定角色
    @observable openModal = null;

    @observable roleList = null;
    @observable roleUserId = null;
    @observable roleUsername = null;
    @observable roleRealname = null;
    @observable userRoles = null;

    @observable errMsg = {
        editUsername: '',
        editPassword: '',
        editRealname: '',
        editCardNo: '',
        editFaceImg: ''
    };

    isEditUserSuccess = false;
    globalErrMsg = '';

    perPage = 10;
    defaultParams = {
        username: '',
        realname: '',
        has_rules: 0,
    };
    queryParams = this.defaultParams;

    @observable isOperationUserBindSuccess = false;
    @observable isFetchUserInfoSuccess = false;

    @computed
    get editFaceImg() {
        return toJS(this.editFaceImgData);
    }

    @computed
    get editCertImgs() {
        return toJS(this.editCertImgsData);
    }

    @computed
    get currentListData() {
        return toJS(this.currentList);
    }

    @computed
    get roleListData() {
        return toJS(this.roleList);
    }

    @computed
    get userRolesData() {
        if (!this.roleList || !this.userRoles) {
            return null;
        }
        return this.roleListData.filter(item => this.userRoles.indexOf(item.id) !== -1).map(item => item.id)
    }

    @computed
    get isEditSubmitBtnDisabled() {
        return !this.editRealname || this.openModal === 1 && !this.isFetchUserInfoSuccess && (!this.editPassword || !this.editUsername);
    }

    @computed
    get isEditRoleSubmitBtnDisabled() {
        return !this.roleList || this.roleList.length < 1;
    }

    @action
    reset() {
        this.username = '';
        this.realname = '';
        this.hasRules = 0;
        this.currentList = null;
        this.isEmptyCondition = true;
        this.perPage = 10;
        this.queryParams = this.defaultParams;
        this.roleList = null;
        this.resetEditUser();
        this.resetRoleModal();
    }

    @action
    resetEditUser() {
        this.editUserId = '';
        this.editUsername = '';
        this.editRealname = '';
        this.editPassword = '';
        this.editCardNo = '';
        this.editFaceImgData = null;
        this.editCertImgsData = null;
        this.isEditUserSuccess = false;
        this.globalErrMsg = '';
        this.errMsg.editUsername = '';
        this.errMsg.editPassword = '';
        this.errMsg.editRealname = '';
        this.errMsg.editCardNo = '';
        this.errMsg.editFaceImg = '';
    }

    @action
    resetRoleModal() {
        this.roleUserId = null;
        this.roleUsername = null;
        this.roleRealname = null;
        this.userRoles = null;
        this.openModal = null;
    }

    @action
    resetQueryParams() {
        this.username = '';
        this.realname = '';
        this.hasRules = 0;
        this.queryParams = this.defaultParams;
    }

    @action
    updateQueryParams() {
        this.queryParams = {
            username: this.username.trim(),
            realname: this.realname.trim(),
            has_rules: this.hasRules || 0,
        }
    }

    @action
    openUserModal(user) {
        if (user) {
            this.editUserId = user.user_id;
            this.editUsername = user.username;
            this.oldUsername = user.username;
            this.editRealname = user.realname;
            this.editCardNo = user.magcard;
            this.editFaceImgData = user.face;
            this.editCertImgsData = user.certifications;
            // this.editFaceImgData = {
            //     download: user.face
            // }
            // if (user.certifications) {
            //     try {
            //         this.editCertImgsData = JSON.parse(user.certifications);
            //     } catch (err) {
            //     }
            // }
            this.openModal = 2;
        } else {
            this.editUserId = '';
            this.editUsername = '';
            this.oldUsername = '';
            this.editRealname = '';
            this.editCardNo = '';
            this.editFaceImgData = null;
            this.editCertImgsData = null;
            this.openModal = 1;
        }
    }
    @action
    closeUserModal() {
        this.editUserId = '';
        this.editUsername = '';
        this.editPassword = '';
        this.editRealname = '';
        this.editCardNo = '';
        this.editFaceImgData = null;
        this.editCertImgsData = null;
        this.openModal = null;
        this.isEditUserSuccess = false;
    }

    @action
    openRoleModal(user) {
        this.roleUserId = user.user_id;
        this.roleUsername = user.username;
        this.roleRealname = user.realname;
        this.userRoles = user.roles && user.roles.map(item => item.id);
        this.openModal = 3;
        !this.roleList && this.fetchRoleList();
    }

    @action
    closeRoleModal() {
        this.resetRoleModal();
    }

    @action
    setUploadFileErr(name, msg) {
        this.errMsg[name] = msg;
    }

    /**
     * 验证用户名
     */
    @action
    validateEditUsername() {
        if (!validationUtil.isMobile(this.editUsername)) {
            this.errMsg.editUsername = noticeMessage.inputFormatError('手机号码');
            return false;
        }
        this.errMsg.editUsername = '';
        return true;
    }

    /**
     * 验证密码
     */
    @action
    validateEditPassword() {
        if (!validationUtil.isSimplePassword(this.editPassword)) {
            this.errMsg.editPassword = noticeMessage.passwordFormatError();
            return false;
        }
        this.errMsg.editPassword = '';
        return true;
    }

    @action
    async fetchListData(page) {
        if (this.queryParams.has_rules !== 1 && this.queryParams.has_rules !== 2) {
            this.queryParams.has_rules = null;
        }
        const res = await this.get('/web-api-compatible/base-ucenter/front-users', {
            ...this.queryParams,
            with_certifications: 1,
            page: page || 1,
            per_page: this.perPage
        }, {
            showGlobalLoading: true,
        });
        runInAction(() => {
            if (res.code === '0000') {
                this.currentList = res.data;
            } else {
                this.currentList = null;
            }
        });
    }

    @action
    async fetchRoleList() {
        const res = await this.get('/auth/all-roles', null, {
            showGlobalLoading: true,
        });
        runInAction(() => {
            if (res.code === '0000') {
                this.roleList = res.data;
            } else {
                this.roleList = null;
            }
        });
    }

    @action
    async editUserSubmit() {
        const openModal = this.openModal;
        this.globalErrMsg = '';
        if (openModal === 1 && !this.isFetchUserInfoSuccess && (!this.validateEditUsername() || !this.validateEditPassword())) {
            return;
        }
        if (openModal === 1 && this.isFetchUserInfoSuccess && this.editPassword && (!this.validateEditUsername() || !this.validateEditPassword())) {
            return;
        }
        if (openModal === 1 && this.isFetchUserInfoSuccess && !this.editPassword && !this.validateEditUsername()) {
            return;
        }
        if (openModal === 2 && this.editPassword && !this.validateEditPassword()) {
            return;
        }
        let url, data, method;
        data = {
            username: this.editUsername,
            password: this.editPassword,
            realname: this.editRealname,
            face: this.editFaceImg,
            certifications: this.editCertImgsData || [],
            // face: this.editFaceImg ? this.editFaceImg.download : '',
            // certifications: this.editCertImgs ? JSON.stringify(this.editCertImgs) : '',
            magcard: this.editCardNo,
        }
        if (openModal === 1) {
            url = '/user/add';
            data.exist_user = this.isFetchUserInfoSuccess ? 1 : 2;
            method = 'post';
        } else {
            url = `/web-api-compatible/base-ucenter/front-users/${this.editUserId}`;
            data.old_username = this.oldUsername;
            method = 'put';
        }
        const res = await this[method](url, data, {
            showGlobalLoading: true,
        });
        const code = res.code;
        runInAction(() => {
            if (code === '0000') {
                this.isEditUserSuccess = true;
            } else if (code === 'UM0004') {
                this.errMsg.editUsername =  openModal === 1 ? '该用户已注册，请前往登录' : '用户已存在，编辑失败';
            } else if (code === 'UM0023') {
                this.errMsg.editCardNo = '卡号已存在，操作失败';
            } else {
                this.globalErrMsg = res.message || (`${openModal === 1 ? '新增' : '编辑'}用户失败，请重试`);
            }
        });
    }

    @action
    async editRoleSubmit() {
        this.globalErrMsg = '';
        this.isEditRoleSuccess = false;
        if (!this.userRolesData) {
            return;
        }
        const res = await this.post(`/auth/user/${this.roleUserId}/roles`, {
            roles: this.userRolesData
        }, {
            showGlobalLoading: true,
        });
        const code = res.code;
        runInAction(() => {
            if (code === '0000') {
                this.isEditRoleSuccess = true;
            } else if (code === '1201') {
                this.globalErrMsg = '没有修改角色的权限，请联系管理员';
            } else {
                this.globalErrMsg = '角色设置失败，请重试';
            }
        });
    }

    @action
    async operationUserBind(operation, user_id) {
        this.globalErrMsg = '';
        this.isOperationUserBindSuccess = false;
        let url;
        if (operation === 'bind') {
            url = '/user/user-bind';
        } else {
            url = '/web-api-compatible/base-ucenter/front-users/unbind';
        }
        const res = await this.post(url, {
            user_id
        }, {
            showGlobalLoading: true
        });
        runInAction(() => {
            if (res.code === '0000') {
                this.isOperationUserBindSuccess = true;
            } else {
                this.globalErrMsg = res.message;
            }
        });
    }

    @action
    async fetchUserInfo(mobile) {
        if (!validationUtil.isMobile(mobile)) {
            return;
        }
        this.isFetchUserInfoSuccess = false;
        const res = await this.get('/user/user/mobile', {
            mobile
        }, {
            showGlobalLoading: true
        });
        runInAction(() => {
            if (res.code === '0000' && res.data) {
                if (!res.data.enterprise_id && res.data.type === 2) {
                    this.isFetchUserInfoSuccess = true;
                    this.editUserId = res.data.user_id;
                    this.editRealname = res.data.real_name;
                    this.editFaceImgData = res.data.face;
                    this.editCertImgsData = res.data.certifications;
                } else if ((res.data.enterprise_id && res.data.type === 2) || res.data.type === 1) {
                    this.errMsg.editUsername = '该号码已被占用';
                } else {
                    this.errMsg.editUsername = null;
                }
            }
        });
    }

}

export default new Store();